package cn.da.shuai.cool.system.service.service.impl;

import cn.da.shuai.cool.mybatis.service.impl.CoolServiceImpl;
import cn.da.shuai.cool.system.service.mapper.CoolDeptMapper;
import cn.da.shuai.cool.system.model.entity.dept.CoolDept;
import cn.da.shuai.cool.system.model.entity.dept.SearchDeptVo;
import cn.da.shuai.cool.system.model.entity.dept.UpdateDeptVo;
import cn.da.shuai.cool.system.model.entity.dept.DeptTreeVo;
import cn.da.shuai.cool.system.service.service.ICoolDeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CoolDeptServiceImpl extends CoolServiceImpl<CoolDeptMapper, CoolDept> implements ICoolDeptService {

    @Override
    public List<CoolDept> listDepartments(SearchDeptVo searchDeptVo) {
        LambdaQueryWrapper<CoolDept> wrapper = Wrappers.lambdaQuery(CoolDept.class)
                .like(searchDeptVo.getDeptName() != null, CoolDept::getDeptName, searchDeptVo.getDeptName())
                .eq(searchDeptVo.getStatus() != null, CoolDept::getStatus, searchDeptVo.getStatus())
                .orderByAsc(CoolDept::getOrderNum);
        return list(wrapper);
    }

    @Override
    public boolean addDepartment(UpdateDeptVo deptVo) {
        CoolDept department = new CoolDept();
        BeanUtils.copyProperties(deptVo, department);
        return save(department);
    }

    @Override
    public boolean updateDepartment(UpdateDeptVo deptVo) {
        CoolDept department = new CoolDept();
        BeanUtils.copyProperties(deptVo, department);
        return updateById(department);
    }

    @Override
    public List<DeptTreeVo> getDepartmentTree() {
        List<CoolDept> allDepts = list(Wrappers.lambdaQuery(CoolDept.class)
                .orderByAsc(CoolDept::getOrderNum));

        Map<Long, List<CoolDept>> parentIdMap = allDepts.stream()
                .collect(Collectors.groupingBy(CoolDept::getParentId));

        return buildDepartmentTree(parentIdMap, 0L);
    }

    private List<DeptTreeVo> buildDepartmentTree(Map<Long, List<CoolDept>> parentIdMap, Long parentId) {
        List<CoolDept> children = parentIdMap.get(parentId);
        if (children == null) {
            return new ArrayList<>();
        }
        List<DeptTreeVo> treeNodes = new ArrayList<>();
        for (CoolDept dept : children) {
            DeptTreeVo treeNode = new DeptTreeVo();
            BeanUtils.copyProperties(dept, treeNode);
            List<DeptTreeVo> childNodes = buildDepartmentTree(parentIdMap, dept.getId());
            treeNode.setChildren(childNodes);
            treeNodes.add(treeNode);
        }
        return treeNodes;
    }
}